<?php
// +----------------------------------------------------------------------
// | 食得鲜API [ shidexian ] 外露数据 [ 上鲜送 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.shidexian.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 何锐 <poptser@foxmail.com>  [ ON THE WAY ]
// +----------------------------------------------------------------------
// | DateTime：2017年4月10日17:36:02
// +----------------------------------------------------------------------
namespace SDXApi\Controller;
use Com\Baidushipping\BaidushippingSubmit;
use Com\Elemeshipping\ElemeshippingSubmit;
use Com\Sdxbsc\SdxbscSubmit;
use Com\Sfshipping\SfshippingSubmit;
use Think\Controller;
use Com\Gkshipping\GkshippingSubmit;
use Think\Log;
class ExposedController extends Controller {
    public function _initialize(){
        header("Access-Control-Allow-Origin: *");
    }
    public function index(){
        /*$admin_user=M('Admin_user');
        $data=$admin_user->select();
        dump($data);*/;
        $this->show('<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} body{ background: #fff; font-family: "微软雅黑"; color: #333;font-size:24px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.8em; font-size: 36px } a,a:hover{color:blue;}</style><div style="padding: 24px 48px;"> <h1>:)</h1><p>欢迎使用 <b>食得鲜 数据平台</b>！</p></div>','utf-8');
        // dump(get_lng_lat('猎德大道46号尚东美御d1102'));

    }

    public function jk(){
        $this->show_cc(1);
    }



    /**
     * 显示生鲜送相关账号下的送达信息  包含 未送达 和 已送达
     */
    public function show_cc($mode = 0){
        set_time_limit(0);
        if($mode==0){
            //$where_mode = " and oa.action_user like '%谭耀辉-出仓%' ";
            $where_mode_new = " and o.distribution_company_id = 3 ";
            $this->assign("show_name",'上鲜送');
            $this->assign("action_name",'show_cc');
        }else{
            //$where_mode = " and oa.action_user like '%广州极客-出仓%' ";
            $where_mode_new = " and o.distribution_company_id = 4 ";
            $this->assign("show_name",'极客');
            $this->assign("action_name",'jk');
        }

        if(IS_POST){
            $start_date = I("post.start_date");
            $end_date = I("post.end_date");
            session("start_date",$start_date);
            session("end_date",$end_date);
            $show = I("post.show");
        }else{
            if(session("start_date")){
                $start_date = session("start_date");
                $end_date = session("end_date");
                $show = I("get.show");
            }else{
                $start_date = date("Y-m-d",time());
                $end_date = date("Y-m-d",time());
                session("start_date",$start_date);
                session("end_date",$end_date);
                $show = I("get.show");
            }
        }

        $this->assign("start_date",$start_date);
        $this->assign("end_date",$end_date);

        if(empty($show)){
            $show = "ing";
        }
        if($show=="complete"){
            //完成订单
            $where= "o.shipping_status =2 and o.pay_status in (2,3) and 
            o.order_status <>2  and o.shipping_id = 3 and 
            o.wdr_id = wdr.id and  o.order_id = oa.order_id and
             TO_DAYS(from_unixtime(o.best_time)) >= TO_DAYS('$start_date') and
             TO_DAYS(from_unixtime(o.best_time)) <= TO_DAYS('$end_date') ".$where_mode_new;
            $this->assign("show",'ing');
            $this->assign("show1",'refund');
            $this->assign("down",'complete');

        }elseif($show=="ing"){
            //进行中订单
            $where= "o.shipping_status !=2 and o.pay_status in (2,3) and 
            o.order_status <>2  and o.shipping_id = 3 and o.outgo = 1 and
            o.wdr_id = wdr.id and o.order_id = oa.order_id 
            and TO_DAYS(from_unixtime(o.best_time)) >= TO_DAYS('$start_date') and
             TO_DAYS(from_unixtime(o.best_time)) <= TO_DAYS('$end_date') ".$where_mode_new;
            $this->assign("show",'complete');
            $this->assign("show1",'refund');
            $this->assign("down",'ing');
        }else{
            //全部退款
            $where= "o.pay_status = 4 and o.shipping_id = 3 and 
            o.wdr_id = wdr.id  and o.order_id = oa.order_id and
             TO_DAYS(from_unixtime(o.best_time)) >= TO_DAYS('$start_date') and
             TO_DAYS(from_unixtime(o.best_time)) <= TO_DAYS('$end_date') ".$where_mode_new;
            $this->assign("show",'ing');
            $this->assign("show1",'complete');
            $this->assign("down",'refund');
        }
        $distribution_cost_all =0;
        $normal_cost_all =0;
        $late_cost_all =0;
        $order_info = M()->table(array('sdx_order_info'=>'o','sdx_warehouse_deliver_region'=>'wdr','sdx_order_action'=>'oa'))
            ->where($where)->field("o.*,wdr.name,wdr.zoning_id,wdr.first_heavy,wdr.continued_heavy")->group('order_id')->order('best_time_start')->select();
        //dump(M()->getlastsql());
        foreach ($order_info as $key=>$value){
//            if($_GET['ts'] ==1){
//                A('Sorting')->send_order_to_gk($value['order_id'],'',469,false);
//            }
            $order_info[$key]['name']=M("zoning_cate")->where(array("id"=>$value['zoning_id']))->getField("name")."-".$value['name'];
            $goods_info = A("Autoserver")->get_goods_list_real($value['order_id'],false,"name");
            $order_info[$key]['goods_name'] = str_replace("\n","<br/>",$goods_info['goods_name']);
            $order_info[$key]['goods_weight'] = $goods_info['goods_weight'];
            $order_info[$key]['goods_num'] = $goods_info['goods_num'];
            $order_info[$key]['address'] = A("Autoserver")->get_address_desc($value['province'], $value['city'], $value['district']).$value['address'].$value['address_name'];
            $order_info[$key]['best_time'] = date("Y-m-d H:i:s",$value['best_time']);
            $order_info[$key]['best_time_start'] = date("Y-m-d H:i:s",$value['best_time_start']);
            $goods_weight = ceil($goods_info['goods_weight']);  //商品重量



            if($value['distribution_company_id']>0){
                $company_area = M("distribution_company_area")->where(array("area_id"=>$value['wdr_id'],"company_id"=>$value['distribution_company_id']))->find();
                $value['first_heavy'] = $company_area['first_money'];
                $value['continued_heavy'] = $company_area['continue_money'];
                $company_info = M("distribution_company")->where(array("id"=>$value['distribution_company_id']))->find();
            }else{
                $company_info['first_num'] = 3;
                $company_info['continue_num'] = 1;
            }

            if($goods_weight>$company_info['first_num']){
                //首重费用和续重费用
                $goods_weight_ext = $goods_weight-$company_info['first_num'];
                $order_info[$key]['distribution_cost'] = $value['first_heavy']+$value['continued_heavy']*($goods_weight_ext/$company_info['continue_num']);
            }else{
                //仅首重费用
                $order_info[$key]['distribution_cost'] = $value['first_heavy'];

            }
            $cold_data = $this->check_goods($goods_info);
            $order_info[$key]['is_cold'] = $cold_data['is_cold'];
            $order_info[$key]['is_ice'] = $cold_data['is_ice'];
            if($value['shipping_status']==2){
                $order_info[$key]['delayed_time'] = round(($value['confirm_time'] - $value['best_time'] + 28800)/3600,1);
                if ($order_info[$key]['delayed_time']<=0){
                    $order_info[$key]['delayed_time'] = "准时";
                    $normal_cost_all += $order_info[$key]['distribution_cost'];
                    $order_info[$key]['order_d_time'] = "normal";
                }else{
                    $late_cost_all += $order_info[$key]['distribution_cost'];
                    $order_info[$key]['order_d_time'] = "late";
                }
            }else{
                $order_info[$key]['delayed_time'] = round(($value['best_time']-time())/3600,1);
                if ($order_info[$key]['delayed_time']<=0){
                    $order_info[$key]['delayed_time'] = "已超时";
                    $late_cost_all += $order_info[$key]['distribution_cost'];
                    $order_info[$key]['order_d_time'] = "late";
                }else{
                    $normal_cost_all += $order_info[$key]['distribution_cost'];
                    $order_info[$key]['order_d_time'] = "normal";
                }
            }
            $distribution_cost_all += $order_info[$key]['distribution_cost'];
        }
        $this->assign("distribution_cost_all",$distribution_cost_all);
        $this->assign("normal_cost_all",$normal_cost_all);
        $this->assign("late_cost_all",$late_cost_all);
        //dump($order_info);
        if(I("get.type")=="down"){
            //下载
            import('Vendor.PHPExcel.PHPExcel');
            import('Vendor.PHPExcel.PHPExcel.Reader.Excel5');
            import('Vendor.PHPExcel.PHPExcel.IOFactory');
            $objPHPExcel = new \PHPExcel();
            $objPHPExcel->getProperties()->setCreator("shidexian@youguoshu")
                ->setLastModifiedBy("shidexian@youguoshu")
                ->setTitle("download file shidexian@youguoshu")
                ->setSubject("shidexian@youguoshu")
                ->setDescription("shidexian@youguoshu")
                ->setKeywords("shidexian")
                ->setCategory("shidexian");

            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(35);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(40);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(5);
            $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(60);
            $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(40);
            $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getStyle('A1:O1')->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->getStyle( 'A1:O1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
            $objPHPExcel->getActiveSheet()->getStyle( 'A1:O1')->getFill()->getStartColor()->setARGB('FF039BE5');

            $objPHPExcel->getActiveSheet()->getStyle('A:O')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $objPHPExcel->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);

            $styleArray = array(
                'borders' => array(
                    'allborders' => array(
                        'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                    ),
                ),
            );

            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，uid是你查出数组的键值，下面以此类推
                ->setCellValue('A1','订单编号')
                ->setCellValue('B1','条形码')
                ->setCellValue('C1','产品名称')
                ->setCellValue('D1','规格(kg)')
                ->setCellValue('E1','数量')
                ->setCellValue('F1','运费')
                ->setCellValue('G1','客人姓名')
                ->setCellValue('H1','电话')
                ->setCellValue('I1','区域')
                ->setCellValue('J1','地址')
                ->setCellValue('K1','标志性建筑')
                ->setCellValue('L1','送达时间范围')
                ->setCellValue('M1','状态')
                ->setCellValue('N1','迟到送达时间')
                ->setCellValue('O1','备注');
            $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);
            $objPHPExcel->getActiveSheet()->getStyle('A1:O1')->applyFromArray($styleArray);


            $files = glob('Uploads/cache/*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
            foreach ($order_info as $k => $v) {

                $cache_code = "Uploads/cache/".$v['order_id'].".jpg";
                $content = file_get_contents('https://w.shidexian.com/buildcode.php?codebar=BCGcode39&text='.$v['order_id']);
                file_put_contents($cache_code, $content);
                switch ($v['shipping_status']){
                    case 1:
                        $shipping_status = "已发货";
                        break;
                    case 2:
                        $shipping_status = "收货确认";
                        break;
                    case 5:
                        $shipping_status = "发货中";
                        break;
                    default:
                        $shipping_status = "未知";
                }
                $num = $k + 2;
                $objPHPExcel->getActiveSheet()->getRowDimension($num)->setRowHeight(90);
                $objPHPExcel->getActiveSheet()->getStyle('A'.$num.':O'.$num)->applyFromArray($styleArray);
                $objPHPExcel->getActiveSheet()->getStyle('B'.$num)->getAlignment()->setWrapText(true);
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValueExplicit('A' . $num, $v['order_sn'],\PHPExcel_Cell_DataType::TYPE_STRING)
                    ->setCellValue('C' . $num, str_replace("<br/>","\n",$v['goods_name']))
                    ->setCellValueExplicit('D' . $num, $v['goods_weight'],\PHPExcel_Cell_DataType::TYPE_STRING)
                    ->setCellValue('E' . $num, $v['goods_num'])
                    ->setCellValue('F' . $num, $v['distribution_cost'])
                    ->setCellValue('H' . $num, $v['consignee'])
                    ->setCellValue('G' . $num, $v['mobile'])
                    ->setCellValue('I' . $num, $v['name'])
                    ->setCellValue('J' . $num, $v['address'])
                    ->setCellValue('K' . $num, $v['sign_building'])
                    ->setCellValue('L' . $num, $v['best_time_start']."-".$v['best_time'])
                    ->setCellValue('M' . $num, $shipping_status)
                    ->setCellValue('N' . $num, $v['delayed_time'])
                    ->setCellValue('O' . $num, $v['postscript']);
                $objDrawing[$num] = new \PHPExcel_Worksheet_Drawing();
                $objDrawing[$num]->setPath($cache_code);
                $objDrawing[$num]->setHeight(96);//照片高度
                $objDrawing[$num]->setWidth(208); //照片宽度
                $objDrawing[$num]->setOffsetX(12);
                $objDrawing[$num]->setOffsetY(12);
                $objDrawing[$num]->setCoordinates('B'.$num);
                $objDrawing[$num]->setWorksheet($objPHPExcel->getActiveSheet());
                //unlink($cache_code);
            }
            $line_num = $num+1;
            $objPHPExcel->getActiveSheet()->mergeCells('A'.$line_num.':O'.$line_num);
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$line_num, "食得鲜订单信息");
            $objPHPExcel->getActiveSheet()->getStyle('A'.$line_num)->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->setTitle('User');
            $objPHPExcel->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="shidexian.xls"');
            header('Cache-Control: max-age=0');
            $write = new \PHPExcel_Writer_Excel5($objPHPExcel);
            $write->save('php://output');
            exit;
        }else{
            $this->assign("order_info",$order_info);
            $this->display('show_cc');
        }

    }


    public function send_order(){
        $order_id = I('post.order_ids');
        $type = 'gk';
        if(empty($order_id)){
            returnApiError('请选择要推送的订单');
        }

        $_POST['store']=1;
        foreach($order_id as $key=>$id){
            $this->send_order_to_gk($id);
        }
        returnApiSuccess('','订单推送完成');
    }

    public function send_order_again(){
        $order_id = I('post.order_id');
        $type = I('post.type','gk');
        $user_id = I('post.user_id');
        if(empty($order_id)){
            returnApiError('请选择要推送的订单');
        }

        switch($type){
            case "eleme":
                $function='send_order_to_eleme';
            break;
            case "bd":
                $function='send_order_to_bd';
            break;
            case "gk":
                $function='send_order_to_gk';
            break;
            case "bsc":
                $function='send_order_to_bsc';
                break;
            case "sf":
                $function='send_order_to_sf';
            break;
            case "sdx":
                $function='send_order_to_sdx';
            break;
            default:
                $function = "";
            break;
        }

        if(empty($function)){
            returnApiError("当前第三方配送暂不支持补推订单");
        }
        $_POST['store']=1;

        $res = $this->$function($order_id,$user_id);

        if($res['error']==1 || $res == false){
            if(empty($res['msg'])){
                $res['msg'] = "订单推送失败，请确定原因后重试";
            }
            returnApiError($res['msg']);
        }else{
            returnApiSuccess('','订单推送完成');
        }
    }


    private function send_order_to_bsc($order_id,$user_id){
        if(empty($order_id)){
            return false;
        }
        $push_bsc = A("Bsc")->post_order($order_id);
        if($push_bsc!==true){
            $data['error'] = 1;
            $data['msg'] = $push_bsc;
        }else{
            $data['error'] = 0;
        }
        return $data;
    }


    /**
     * todo 推送订单到极客配送
     * @param $order_id
     * @param $order
     * @param $user_id
     * @param $show_return
     * @return bool
     */
    private function send_order_to_gk($order_id,$user_id){
        if(empty($order_id)){
            return false;
        }
        $where['order_id'] = $order_id;
        $order = M("order_info")->where($where)->find();

        if(empty($order)){
            return false;
        }

//        if(!$order['outgo_id'] || !in_array($order['outgo_id'],C('gk_chucang_user_id'))){
//            return false;
//        }
        //订单送货地址信息
        $province_name=M('region')->where('region_id ='.$order['province'])->getField('region_name');
        $city_name=M('region')->where('region_id ='.$order['city'])->getField('region_name');
        $district_name=M('region')->where('region_id ='.$order['district'])->getField('region_name');

        //获取订单商品信息
        $goods_field = "goods_id,goods_name as name,goods_price as price,goods_number as quantity,goods_price*goods_number as total";
        $order_goods = M('order_goods')->field($goods_field)->where(array('order_id'=>$order['order_id']))->select();

        $total_quantity = 0;
        $total_weight = 0;
        foreach ($order_goods as $key=>$value){
            $goods_id = $value['goods_id'];
            $goods_weight = M("goods")->where(array("goods_id"=>$goods_id))->getField("goods_weight");
            $sum_refund_number = A('Sorting')->get_goods_refund_num($order['order_id'],$value['goods_id']);
            if($value['quantity']-$sum_refund_number<=0){
                unset($order_goods[$key]);
                continue;
            }
            $order_goods[$key]['value'] = $goods_weight;
            $order_goods[$key]['model'] = $goods_weight."kg";
            $order_goods[$key]['deliver_cid'] = 7;
            $total_quantity+=$value['quantity'];
            $total_weight+=$goods_weight*$value['quantity'];
            unset($order_goods[$key]['goods_id']);
        }

        $order_goods = array_values($order_goods);

        $order_bag = S('order_bag_'.$order['order_id']);
        if(!empty($order_bag)){
            $order_goods = array();
            foreach ($order_bag as $order_item){
                $tmp_order_item = array();
                $type_name = $this->get_bag_type_name($order_item['type']);
                $tmp_order_item['name'] =$type_name.$order_item['current'];
                $tmp_order_item['price'] =1;
                $tmp_order_item['value'] =1;
                $tmp_order_item['quantity'] =1;
                $tmp_order_item['total'] =1;
                $tmp_order_item['model'] ='1kg';
                $tmp_order_item['deliver_cid'] =7;
                $tmp_order_item['product_no'] =$order['order_sn'].str_pad($order_item['all'],2,"0",STR_PAD_LEFT).str_pad($order_item['current'],2,"0",STR_PAD_LEFT).$order_item['type'];

                $order_goods[] = $tmp_order_item;
            }
        }

        $receiver_address = $province_name.$city_name.$district_name;
        $receiver_address .= $order['address'];
        if(!empty($order['sign_building'])){
            $receiver_address.= $order['sign_building'];
        }
        if(!empty($order['address_name'])){
            $receiver_address.= $order['address_name'];
        }

        if($order['shipping_extend_status']==4){
            $new_order_sn = $this->get_repush_order_sn($order['order_sn'],'gk');
        }else{
            $new_order_sn = $order['order_sn'];
        }

        $_POST['store']=1;

        $sender_info_list = C('gk_sender_info');
        $sender_info = $sender_info_list[$order['wid']];
        //订单取货地址信息
        $sender_province_name=M('region')->where('region_id ='.$sender_info['sender_province'])->getField('region_name');
        $sender_city_name=M('region')->where('region_id ='.$sender_info['sender_city'])->getField('region_name');
        $sender_district_name=M('region')->where('region_id ='.$sender_info['sender_district'])->getField('region_name');

        $verify_code = A('Distribution')->get_order_receipt_code($order['order_id']);

        $order_shipping_info = array(
            'order_no' => $new_order_sn,
            'receiver' => $order['consignee'],
            'receiver_telephone' => $order['mobile'],
            'receiver_province' => $province_name,
            'receiver_city' => $city_name,
            'receiver_district' => $district_name,
            'receiver_address' => $receiver_address,
//            'receiver_longitude'  => $order['longitude'],
//            'receiver_latitude'  => $order['latitude'],
            'sender'=>$sender_info['sender'],
            'sender_telephone'=>$sender_info['sender_telephone'],
            'sender_province'=>$sender_province_name,
            'sender_city'=>$sender_city_name,
            'sender_district'=>$sender_district_name,
            'sender_address'=>$sender_info['sender_address'],
            'payment_method' => '线上已支付',
            'total' => '0',
            'weight' => $total_weight,
            'quantity' => $total_quantity,
            'comment' => $order['postscript'],
            'products' =>$order_goods,
            'deliver_time' => date('Y-m-d H:i:s',$order['best_time_start']),
            'deliver_time_end' => date('Y-m-d H:i:s',$order['best_time']),
            'verify_code' =>$verify_code
        );

        $this->write_log("gk test data: ".json_encode($order_shipping_info),'gk_shipping');
        //推送订单
        $Gk_Submit = new GkshippingSubmit();
        $res = $Gk_Submit->postOrder($order_shipping_info);

        $this->write_log("gk test: ".json_encode($res),'gk_shipping');

        if(empty($user_id)){
            $user_id = $order['outgo_id'];
        }
        if($res['result']=='fail'){
            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")补推送失败，".$res['info'],array(),array(),false);
            $return_data['error'] = 1;
            $return_data['msg'] = "订单(".$order['order_sn'].")出仓失败，".$res['info'];
            return $return_data;
        }else{
            $order_data = array(
                'shipping_extend_type'=>'gk',
                'shipping_extend_status'=>0
            );
            M("order_info")->where(array('order_id'=>$order['order_id']))->save($order_data);

            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")补推送成功。",array(),array(),false);
        }

        return true;
    }

    public function send_order_to_bd($order_id,$user_id){
        if(empty($order_id)){
            return false;
        }

        $where['order_id'] = $order_id;
        $order = M("order_info")->where($where)->find();

        if(empty($order)){
            return false;
        }
        //订单送货地址信息
        $province_name=M('region')->where('region_id ='.$order['province'])->getField('region_name');
        $city_name=M('region')->where('region_id ='.$order['city'])->getField('region_name');
        $district_name=M('region')->where('region_id ='.$order['district'])->getField('region_name');

        //获取订单商品信息
        $goods_field = "goods_id,goods_name as dish_name,goods_price as dish_unit_price,goods_number as dish_number,goods_price*goods_number as dish_total_price";
        $order_goods = M('order_goods')->field($goods_field)->where(array('order_id'=>$order['order_id']))->select();

        $product_price = 0;
        foreach ($order_goods as $key=>$value){
            $sum_refund_number = A('Sorting')->get_goods_refund_num($order['order_id'],$value['goods_id']);
            if($value['dish_number']-$sum_refund_number<=0){
                unset($order_goods[$key]);
                continue;
            }
            $product_price += $value['dish_total_price'];
            unset($order_goods[$key]['goods_id']);
        }

        $order_goods = array_values($order_goods);
        $receiver_address = $province_name.$city_name.$district_name;
        $receiver_address .= $order['address'];
        if(!empty($order['sign_building'])){
            $receiver_address.= $order['sign_building'];
        }
        if(!empty($order['address_name'])){
            $receiver_address.= $order['address_name'];
        }

        $_POST['store']=1;
        $order['order_amount'] = $order['order_amount']+$order['surplus']+$order['money_paid'];
        $order['order_amount'] = round($order['order_amount'],2);
        $order_detail = array(
            'product_price'=>$product_price,
            'products'=>$order_goods
        );

        $baidu_order_sequence = S('baidu_order_sequence'.date("d"));
        $count = $baidu_order_sequence[$order['order_id']];

        $order_time = localtotime($order['add_time']);
        $order_time_today = localtotime(gmtime());
        if(($order_time_today-$order_time)-(24*60*60*2)>0){
            $order_time = $order_time_today;
        }

        $order_shipping_info = array(
            'out_order_id' => $order['order_sn'],
            'order_index'=>$count,
            'user_phone' => $order['mobile'],
            'user_address' => $receiver_address,   //北京市工人体育馆
            //            'user_address' => "北京市工人体育馆",   //北京市工人体育馆
            'user_name' => $order['consignee'],
            'user_longitude'  => $order['longitude'],  //116.457945
            'user_latitude'  => $order['latitude'],    //"39.931679"
            //            'user_longitude'  => "116.457945",  //116.457945
            //            'user_latitude'  => "39.931679",    //"39.931679"
            'wl_shop_id'=> C('bd_wl_shop_id'),
            'shop_phone'=>C('shop_phone'),
            'order_time'=>$order_time,
            'expect_time_mode'=>1,
            'expect_time_start' => $order['best_time_start'],
            'expect_time' => $order['best_time_start']+3600*1.5, //$order['best_time']
            'shop_price'=> "0.00",
            'user_price'=> "0.00",
            'user_total_price'=> $order ['order_amount'],
            'remark' => $order['postscript'],
            'pay_type'=>1,
            'source_name'=>C('bd_source'),
            'order_detail'=>$order_detail,
            'push_time'=>time(),
            'app_id'=>C('bd_app_id')
        );
        $this->write_log("bd test data: ".json_encode($order_shipping_info),'bd_shipping');
        //推送订单
        $Bd_Submit = new BaidushippingSubmit();
        $res = $Bd_Submit->postOrder($order_shipping_info);

        $this->write_log("bd test: ".json_encode($res),'bd_shipping');

        if($res['error_no']!=0){
            $error_msg = $Bd_Submit->get_post_error_msg();
            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")补推送失败，".$error_msg[$res['error_no']]."(".$res['message'].")",array(),array(),false);
            $return_data['error'] = 1;
            $return_data['msg'] = "订单(".$order['order_sn'].")出仓失败，".$res['message'];
            return $return_data;
        }else{
            $order_data = array(
                'shipping_extend_type'=>'bd',
                'shipping_extend_status'=>0
            );
            M("order_info")->where(array('order_id'=>$order['order_id']))->save($order_data);

            $return_data = $res['result'];
            $shipping_extend_order_id = $return_data['order_id'];
            $this->save_shipping_extend_order_id($order['order_id'],$shipping_extend_order_id);
            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")补推送成功。",array(),array(),false);
        }
        return true;
    }

    /**
     * todo 推送订单到蜂鸟配送
     * @param $order_id
     * @param $order
     * @param $user_id
     * @param $show_return
     * @return bool
     */
    public function send_order_to_eleme($order_id,$user_id){
        if(empty($order_id)){
            return false;
        }

        $where['order_id'] = $order_id;
        $order = M("order_info")->where($where)->find();

        if(empty($order)){
            return false;
        }
        //订单送货地址信息
        $province_name=M('region')->where('region_id ='.$order['province'])->getField('region_name');
        $city_name=M('region')->where('region_id ='.$order['city'])->getField('region_name');
        $district_name=M('region')->where('region_id ='.$order['district'])->getField('region_name');

        //获取订单商品信息
        $goods_field = "og.goods_id,og.goods_name as item_name,mp.user_price as item_price,og.goods_price as item_actual_price,og.goods_number as item_quantity";
        $order_goods = M('order_goods')
            ->alias('og')
            ->field($goods_field)
            ->join('left join '.C('DB_PREFIX').'member_price mp on og.goods_id=mp.goods_id')
            ->where(array('og.order_id'=>$order['order_id'],'mp.user_rank'=>1))
            ->select();

        $total_quantity = 0;
        $total_weight = 0;
        $order_total_amount = 0;
        $order_actual_amount = 0;
        foreach ($order_goods as $key=>$value){
            $goods_id = $value['goods_id'];
            $goods_weight = M("goods")->where(array("goods_id"=>$goods_id))->getField("goods_weight");
            $sum_refund_number = A('Sorting')->get_goods_refund_num($order['order_id'],$goods_id);
            if($value['item_quantity']-$sum_refund_number<=0){
                unset($order_goods[$key]);
                continue;
            }
            $order_goods[$key]['item_quantity'] = $value['item_quantity']-$sum_refund_number;
            $order_goods[$key]['is_need_package'] = C('eleme_is_need_package');
            $order_goods[$key]['is_agent_purchase'] = C('eleme_is_agent_purchase');
            $total_quantity+=$value['item_quantity']-$sum_refund_number;
            $total_weight+=$goods_weight*($value['item_quantity']-$sum_refund_number);
            $order_total_amount+=($value['item_quantity']-$sum_refund_number)*$value['item_price'];
            $order_actual_amount+=($value['item_quantity']-$sum_refund_number)*$value['item_actual_price'];
            unset($order_goods[$key]['goods_id']);
        }

        $order_goods = array_values($order_goods);

        $order_bag = S('order_bag_'.$order['order_id']);
        if(!empty($order_bag)){
            $order_goods = array();
            foreach ($order_bag as $order_item){
                $tmp_order_item = array();
                $type_name = $this->get_bag_type_name($order_item['type']);
                $tmp_order_item['item_id'] =$order['order_sn'].str_pad($order_item['all'],2,"0",STR_PAD_LEFT).str_pad($order_item['current'],2,"0",STR_PAD_LEFT).$order_item['type'];
                $tmp_order_item['item_name'] =$type_name.$order_item['current'];
                $tmp_order_item['item_quantity'] =1;
                $tmp_order_item['item_price'] =1;
                $tmp_order_item['item_actual_price'] =1;
                $tmp_order_item['is_need_package'] = C('eleme_is_need_package');
                $tmp_order_item['is_agent_purchase'] = C('eleme_is_agent_purchase');

                $order_goods[] = $tmp_order_item;
            }
        }

        $receiver_address = $province_name.$city_name.$district_name;
        $receiver_address .= $order['address'];
        if(!empty($order['sign_building'])){
            $receiver_address.= $order['sign_building'];
        }
        if(!empty($order['address_name'])){
            $receiver_address.= $order['address_name'];
        }

        $_POST['store']=1;
        $transport_info_list = C('eleme_transport_info');
        $transport_info = $transport_info_list[$order['wid']];

        $baidu_order_sequence = S('baidu_order_sequence'.date("d"));
        $count = $baidu_order_sequence[$order['order_id']];

        $order_shipping_info = array(
            'transport_info' => $transport_info,
            'receiver_info' => array(
                'receiver_name' => $order['consignee'],
                'receiver_primary_phone' => $order['mobile'],
                'receiver_address' => $receiver_address,
                'receiver_longitude' => $order['longitude'],
                'position_source' => $transport_info['position_source'],
                'receiver_latitude' => $order['latitude']
            ),
            'items_json' => $order_goods,
            'partner_remark' => '食得鲜',
            'partner_order_code' => $order['order_sn'],     // 第三方订单号, 需唯一
            'notify_url' => C('eleme_notify_url'),     //第三方回调 url地址
            'order_type' => 1,
            'order_total_amount' => $order_total_amount,
            'order_actual_amount' => $order_actual_amount,
            'order_weight'=> $total_weight,
            'is_invoiced' => 0,
            'invoice' => C('eleme_invoice'),
            'order_payment_status' => 1,
            'order_payment_method' => 1,
            'goods_count' => $total_quantity,
            'is_agent_payment' => 0,
            'require_receive_time' => ($order['best_time_start']+3600*1.5) * 1000,  //注意这是毫秒数
            'serial_number'=>$count
        );

        $this->write_log("eleme test data: ".json_encode($order_shipping_info),'eleme_shipping');
        //推送订单
        $Gk_Submit = new ElemeshippingSubmit();
        $res = $Gk_Submit->sendOrder($order_shipping_info);

        $this->write_log("eleme test: ".json_encode($res),'eleme_shipping');

        if((empty($res) || $res['code']!='200')){
            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")补推送失败，".$res['msg'],array(),array(),false);
            $return_data['error'] = 1;
            $return_data['msg'] = "订单(".$order['order_sn'].")出仓失败，".$res['msg'];
            return $return_data;
        }else{
            $order_data = array(
                'shipping_extend_type'=>'eleme',
                'shipping_extend_status'=>0
            );
            M("order_info")->where(array('order_id'=>$order['order_id']))->save($order_data);

            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")补推送成功。",array(),array(),false);
        }
        return true;
    }

    /**
     * todo 推送订单到顺丰配送
     * @param $order_id
     * @param $order
     * @param $user_id
     * @param $show_return
     * @return bool
     */
    public function send_order_to_sf($order_id,$user_id){
        if(empty($order_id)){
            return false;
        }

        $where['order_id'] = $order_id;
        $order = M("order_info")->where($where)->find();

        if(empty($order)){
            return false;
        }
        //订单送货地址信息
        $province_name=M('region')->where('region_id ='.$order['province'])->getField('region_name');
        $city_name=M('region')->where('region_id ='.$order['city'])->getField('region_name');
        $district_name=M('region')->where('region_id ='.$order['district'])->getField('region_name');

        //获取订单商品信息
        $goods_field = "goods_id,goods_name,goods_price,goods_number";
        $order_goods = M('order_goods')->field($goods_field)->where(array('order_id'=>$order['order_id']))->select();

        $total_quantity = 0;
        $total_weight = 0;
        $order_total_amount = 0;
        $order_goods_temp = array();
        foreach ($order_goods as $key=>$value){
            $goods_id = $value['goods_id'];
            $goods_weight = M("goods")->where(array("goods_id"=>$goods_id))->getField("goods_weight");
            $sum_refund_number =  A('Sorting')->get_goods_refund_num($order['order_id'],$goods_id);
            if($value['goods_number']-$sum_refund_number<=0){
                unset($order_goods[$key]);
                continue;
            }
            $order_goods_temp[$key]['itemName'] = $value['goods_name'];
            $order_goods_temp[$key]['itemPrice'] = $value['goods_price'];
            $order_goods_temp[$key]['itemQty'] = $value['goods_number']-$sum_refund_number;
            $order_goods_temp[$key]['currency'] = 'CNY';
            $order_goods_temp[$key]['itemWeight'] = $goods_weight;
            $order_goods_temp[$key]['itemModel'] = '';
            $order_goods_temp[$key]['itemVolume'] = '';
            $order_goods_temp[$key]['itemMemo'] = '';

            $total_quantity+=$value['goods_number']-$sum_refund_number;
            $total_weight+=$goods_weight*($value['goods_number']-$sum_refund_number);
            $order_total_amount+=($value['goods_number']-$sum_refund_number)*$value['goods_price'];
            unset($order_goods[$key]['goods_id']);
        }

        $order_goods = array_values($order_goods_temp);

        $order_bag = S('order_bag_'.$order['order_id']);
        if(!empty($order_bag)){
            $total_quantity = 0;
            $order_goods = array();
            foreach ($order_bag as $order_item){
                $tmp_order_item = array();
                $type_name = $this->get_bag_type_name($order_item['type']);
                $tmp_order_item['itemName'] =$type_name.$order_item['current'];
                $tmp_order_item['itemQty'] =1;
                $tmp_order_item['itemPrice'] =1;
                $tmp_order_item['currency'] = 'CNY';
                $tmp_order_item['itemWeight'] =0.0;
                $tmp_order_item['itemModel'] = '';
                $tmp_order_item['itemVolume'] = '';
                $tmp_order_item['itemMemo'] = '';
                $order_goods[] = $tmp_order_item;
                $total_quantity+=1;
            }
        }

        $receiver_address = $province_name.$city_name.$district_name;
        $address = $order['address'];
        //        $receiver_address .= $order['address'];
        if(!empty($order['sign_building'])){
            if(!empty($receiver_address)){
                $address.= "-".$order['sign_building'];
            }else{
                $address.= $order['sign_building'];
            }
        }
        if(!empty($order['address_name'])){
            if(!empty($receiver_address)){
                $address.= "-".$order['address_name'];
            }else{
                $address.= $order['address_name'];
            }
        }

        $_POST['store']=1;

        if($order['shipping_extend_status']==4){
            $order['order_sn'] = $this->get_repush_order_sn($order['order_sn'],'sf');
        }

        $baidu_order_sequence = S('baidu_order_sequence'.date("d"));
        $count = $baidu_order_sequence[$order['order_id']];
        $sf_config = C('SF_CONFIG');

        $transport_info_list = $sf_config['SHOP_INFO'];
        $transport_info = $transport_info_list[$order['wid']];

        $order_shipping_info = array(
            'order'=>array(
                'orderNo'=>$order['order_sn'],
                'orderAmount'=>$order_total_amount,
                'payMethod'=>1,
                'payStatus'=>1,
                'receivable'=>0,
                'rewardFee'=>0,
                'currency'=>'CNY',
                'category'=>6,
                'totalWeight'=>$total_weight,
                'totalVolume'=>'',
                'totalQty'=>$total_quantity,
                'daySequence'=>$count
            ),
            'itemDetails'=>$order_goods,
            'send'=>array(
                'storeName'=>$transport_info['STORENAME'],
                'storeCode'=>$transport_info['STORECODE'],
                'addressProvince'=>$transport_info['ADDRESSPROVINCE'],
                'addressCity'=>$transport_info['ADDRESSCITY'],
                'addressDistrict'=>$transport_info['ADDRESSDISTRICT'],
                'address'=>$transport_info['ADDRESS'],
                'contacts'=>$transport_info['CONTACTS'],
                'mobile'=>$transport_info['MOBILE']

            ),
            'receive'=>array(
                'addressProvince'=>$province_name,
                'addressCity'=>$city_name,
                'addressDistrict'=>$district_name,
                'address'=>$address,
                'contacts'=>$order['consignee'],
                'mobile'=>$order['mobile']
            ),
        );

        $this->write_log("sf test data: ".json_encode($order_shipping_info),'sf_shipping');
        //推送订单
        $SF_Submit = new SfshippingSubmit();
        $res = $SF_Submit->order_service($order_shipping_info);

        $this->write_log("sf test: ".json_encode($res),'sf_shipping');

        if((empty($res) || $res['status']!='100')){
            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")补推送失败，".$res['message'],array(),array(),false);
            $return_data['error'] = 1;
            $return_data['msg'] = "订单(".$order['order_sn'].")出仓失败，".$res['message'];
            return $return_data;
        }else{
            $order_data = array(
                'shipping_extend_type'=>'sf',
                'shipping_extend_status'=>0
            );
            M("order_info")->where(array('order_id'=>$order['order_id']))->save($order_data);

            $shipping_extend_order_id = $res['sfOrderNo'];
            A('Sorting')->save_shipping_extend_order_id($order['order_id'],$shipping_extend_order_id);

            A('Gkshipping')->add_order_action($order['order_sn'],$user_id,"订单(".$order['order_sn'].")补推送成功。",array(),array(),false);
        }
        return true;
    }


    /**
     * @param $order_id
     * @param $order_info
     * @param $user_id
     * @param bool $show_return
     * @return bool
     */
    public function send_order_to_sdx($order_id,$user_id){
        if(empty($order_id)){
            return false;
        }

        $where['order_id'] = $order_id;
        $order_info = M("order_info")->where($where)->find();

        if(empty($order_info)){
            return false;
        }
        $data = array();

        //获取取货点配置信息
        $sdx_bsc_config = C('SDX_BSC_CONFIG');

        $pickup_point_list = $sdx_bsc_config['WAREHOUSE'];
        $pickup_point_info = $pickup_point_list[$order_info['wid']];
        //设置取货点id
        $data['scc_id'] = $pickup_point_info['scc_id'];

        $data['third_sn'] = $order_info['order_sn'];    //订单号
        $data['consignee'] = $order_info['consignee'];   //收货人姓名
        $data['mobile'] = $order_info['mobile'];      //手机号
        $data['province'] = M('region')->where(array('region_id'=>$order_info['province']))->getField('region_name');    //省份
        $data['city'] = M('region')->where(array('region_id'=>$order_info['city']))->getField('region_name');        //城市
        $data['district'] = M('region')->where(array('region_id'=>$order_info['district']))->getField('region_name');    //区县
        $data['address'] = $order_info['address'].$order_info['address_name'];     //详细地址

        if($order_info['longitude']>$order_info['latitude']){
//            $data_gps =GCJ02_To_BD09($order_info['longitude'],$order_info['latitude']);
            $longitude = $order_info['latitude'];
            $latitude = $order_info['longitude'];
        }else{
//            $data_gps =GCJ02_To_BD09($order_info['latitude'],$order_info['longitude']);
            $longitude = $order_info['latitude'];
            $latitude = $order_info['longitude'];
        }


        $data['longitude'] = $longitude;   //经度
        $data['latitude'] = $latitude;    //纬度

        $data['landmarks'] = $order_info['sign_building'];   //地标
        $data['delivery_start_time'] = $order_info['best_time_start']; //开始配送时间
        $data['delivery_end_time'] = $order_info['best_time'];   //结束配送时间
        $data['remark'] = $order_info['postscript'];   //订单备注

        $_POST['store'] = 1;
        $goods_list = A('Bsc')->get_goods_list_real($order_info['order_id']);

        //订单商品数量
        $order_bag = S('order_bag_'.$order_info['order_id']);
        if(!empty($order_bag)){
            $order_goods = array();
            foreach ($order_bag as $order_item){
                $tmp_order_item = array();
                $type_name = $this->get_bag_type_name($order_item['type']);
                $tmp_order_item['goods_name'] =$type_name.$order_item['current'];
                $tmp_order_item['goods_price'] =0;
                $tmp_order_item['goods_sn'] =$order_info['order_sn'].str_pad($order_item['all'],2,"0",STR_PAD_LEFT).str_pad($order_item['current'],2,"0",STR_PAD_LEFT).$order_item['type'];
                $tmp_order_item['goods_number'] =1;
                $tmp_order_item['goods_weight'] =1;
                $order_goods[] = $tmp_order_item;
            }
            $order_weight = 0;
            foreach ($goods_list as $key=>$value){
                $order_weight += $value['goods_weight']*$value['goods_number'];
            }

            $data['order_weight'] = $order_weight;   //订单重量指定
            $data['goods_num'] = count($order_goods);    //订单商品袋数

            $data['goods'] = $order_goods;
        }else{
            $data['goods'] = $goods_list;
        }
        $data['order_freight'] = A('Sorting')->get_order_freight($order_info['wdr_id'],$order_info['distribution_company_id'],$order_weight);
        if($order_info['shipping_extend_status']==8){
            $data['repush_order'] = 1;
        }

        $sdx_bsc = new SdxbscSubmit();
        $post_value_array = $sdx_bsc->post_order($data);
        if($post_value_array['status']==1){
            //成功推送至BSC
            $this->write_log($order_info['order_sn'],'sdx_bsc_ok');

            $order_data = array(
                'shipping_extend_type'=>'sdx',
                'shipping_extend_status'=>0,
                'push_bsc'=>2
            );
            M("order_info")->where(array('order_id'=>$order_info['order_id']))->save($order_data);

            A('Sorting')->save_shipping_extend_order_id($order_info['order_id'], $post_value_array['order_sn']);
            A('Gkshipping')->add_order_action($order_info['order_sn'],$user_id,"订单(".$order_info['order_sn'].")补推送成功。",array(),array(),false);
        }else{
            //推送至BSC失败
            $this->write_log($order_info['order_sn']." CODE:".$post_value_array['err_code']." msg:".$post_value_array['error_msg'],'sdx_bsc_fail');
            $return_data['error'] = 1;
            $return_data['msg'] = "订单(".$order_info['order_sn'].")补推送失败，".$post_value_array['error_msg'];
            A('Gkshipping')->add_order_action($order_info['order_sn'],$user_id,"订单(".$order_info['order_sn'].")补推送失败，".$post_value_array['error_msg'],array(),array(),false);
            return $return_data;
        }

        return true;
    }

    /**
     * @param $order_sn
     * @param string $tip
     * @param int $length
     * @return string
     */
    private function get_repush_order_sn($order_sn,$tip='gk',$length=5){
        $str='0123456789';
        $rndstr ='';
        for($i=0;$i<$length;$i++){
            $rndcode=rand(0,9);
            $rndstr.=$str[$rndcode];
        }
        return $order_sn.$tip.$rndstr;
    }



    private function get_bag_type_name($type){
        $name = "";
        switch ($type){
            case "1":
                $name="藏";
            break;
            case "2":
                $name="冻";
            break;
            case "0":
                $name="常";
            break;
        }
        return $name;
    }

    private function write_log($message,$filename){
        $log = new Log();
        $destination = C('LOG_PATH').date('y_m_d').'_'.$filename.'.log';

        $log->write($message,'DEBUG','',$destination);
    }

    /**
     *异步查询订单操作信息和基础信息
     */
    public function notify_select($order_sn){
        if (empty($order_sn)) return false;
        $sql = "SELECT sdx_order_action.* FROM  sdx_order_action,sdx_order_info WHERE sdx_order_info.order_id = sdx_order_action.order_id and sdx_order_info.order_sn = '".$order_sn."'";
        $data_s = M()->query($sql);
        foreach ($data_s as $kk=>$vv){

            $data_s[$kk]['log_time'] = local_date('Y-m-d H:i:s',$vv['log_time']);

            switch ($vv['order_status']){
                case 0:
                    $data_s[$kk]['order_status'] = "未确认";
                    break;
                case 1:
                    $data_s[$kk]['order_status'] = "已确认";
                    break;
                case 2:
                    $data_s[$kk]['order_status'] = "已取消";
                    break;
                case 3:
                    $data_s[$kk]['order_status'] = "无效";
                    break;
                case 4:
                    $data_s[$kk]['order_status'] = "退货";
                    break;
                case 5:
                    $data_s[$kk]['order_status'] = "已发货";
                    break;
            }

            switch ($vv['shipping_status']){
                case 0:
                    $data_s[$kk]['shipping_status'] = "未发货";
                    break;
                case 1:
                    $data_s[$kk]['shipping_status'] = "已发货";
                    break;
                case 2:
                    $data_s[$kk]['shipping_status'] = "已收货";
                    break;
                case 3:
                    $data_s[$kk]['shipping_status'] = "备货中";
                    break;
                case 4:
                    $data_s[$kk]['shipping_status'] = "备货中";
                    break;
                case 5:
                    $data_s[$kk]['shipping_status'] = "已备货";
                    break;
                case 7:
                    $data_s[$kk]['shipping_status'] = "--";
                    break;
            }


            switch ($vv['pay_status']){
                case 0:
                    $data_s[$kk]['pay_status'] = "未付款";
                    break;
                case 1:
                    $data_s[$kk]['pay_status'] = "付款中";
                    break;
                case 2:
                    $data_s[$kk]['pay_status'] = "已付款";
                    break;
                case 3:
                    $data_s[$kk]['pay_status'] = "部分退款";
                    break;
                case 4:
                    $data_s[$kk]['pay_status'] = "全部退款";
                    break;
            }
        }

        $data['order_action'] = $data_s;

        $sql_order_info = "SELECT consignee,province,city,district,address,mobile,best_time,best_time_start,shipping_id,sign_building FROM  sdx_order_info WHERE order_sn = '".$order_sn."'";
        $data_order_info = M()->query($sql_order_info);

        $data_order_info = $data_order_info[0];

        $data['username'] = $data_order_info['consignee'];
        $data['userphone'] = $data_order_info['mobile'];
        $data['address'] = $data_order_info['sign_building']."(".$data_order_info['address'].")";
        $data['best_time'] = $data_order_info['best_time'];
        $data['best_time_start'] = $data_order_info['best_time_start'];



        if ($data['best_time'] == 0) {
            $data['best_time_2'] = "无期望时间";
        } else {


            if ($data['best_time_start']) {
                $data['best_time_2'] = date('Y-m-d H:i:s', $data['best_time_start']) . "-" . date('Y-m-d H:i:s', $data['best_time']);
            } else {
                if ($data['is_presell'] == 1) {
                    //预售单
                    $order['best_time_2'] = date('Y-m-d' . " 10:00:00", $data['best_time']) . "  -   " . date('Y-m-d' . " 20:30:00", $data['best_time']);
                } else {
                    if ($data['shipping_id'] == 2) {
                        //自提订单
                        $order['best_time_2'] = date('Y-m-d' . " 10:00:00", $data['best_time']) . "  -   " . date('Y-m-d' . " 20:30:00", $data['best_time']);
                    } else {
                        $order['best_time_2'] = date('Y-m-d H:i:s', $data['best_time'] - 7199) . "  -   " . date('Y-m-d H:i:s', $data['best_time'] + 1);
                    }
                }
            }
        }

        echo json_encode($data);
    }
    /**
     * TODO 检查商品中是否有冷冻冷藏商品
     * @param $goods_list
     * @return mixed
     */
    private function check_goods($goods_list) {

        $re_data['is_cold'] = 0;    //冷冻
        $re_data['is_ice'] = 0;     //冷藏

        foreach ($goods_list as $value){
            if($re_data['is_cold']==0||$re_data['is_ice']==0){
                $goods_cat_id = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField("cat_id");

                $cat_id = M("category")->field("parent_id,temperature")->where(array("cat_id"=>$goods_cat_id))->find();

                if(empty($cat_id['temperature'])&&!empty($cat_id['parent_id'])){

                    $cat_2 = M("category")->field("parent_id,temperature")->where(array("cat_id"=>$cat_id['parent_id']))->find();
                    if(empty($cat_2['temperature'])&&!empty($cat_2['parent_id'])){
                        $cat_3 = M("category")->field("parent_id,temperature")->where(array("cat_id"=>$cat_2['parent_id']))->find();
                        //dump($cat_3);
                        if(!empty($cat_3['temperature'])){
                            if($cat_3['temperature']==2){
                                $re_data['is_cold'] = 1;
                            }
                            if($cat_3['temperature']==3){
                                $re_data['is_ice'] = 1;
                            }
                        }
                    }else{
                        if($cat_2['temperature']==2){
                            $re_data['is_cold'] = 1;
                        }
                        if($cat_2['temperature']==3){
                            $re_data['is_ice'] = 1;
                        }
                    }
                }else{
                    if($cat_id['temperature']==2){
                        $re_data['is_cold'] = 1;
                    }
                    if($cat_id['temperature']==3){
                        $re_data['is_ice'] = 1;
                    }
                }

//
//
//
//
//
//
//
//                if(empty($cat_id)){
//                    if($goods_cat_id==192){
//                        $re_data['is_ice']=1;
//                    }
//                    if($goods_cat_id==703){
//                        $re_data['is_cold']=1;
//                    }
//                }else{
//                    $cat_ids = M("category")->where(array("cat_id"=>$cat_id))->getField("parent_id");
//                    if(empty($cat_ids)){
//                        if($cat_id==192){
//                            $re_data['is_ice']=1;
//                        }
//                        if($cat_id==703){
//                            $re_data['is_cold']=1;
//                        }
//                    }else{
//                        $cat_idp = M("category")->where(array("cat_id"=>$cat_ids))->getField("parent_id");
//                        if(empty($cat_idp)){
//                            if($cat_ids==192){
//                                $re_data['is_ice']=1;
//                            }
//                            if($cat_ids==703){
//                                $re_data['is_cold']=1;
//                            }
//                        }
//                    }
//                }
            }
        }
        return $re_data;
    }
}